package models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Author;


public class AuthorModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "author_";
	
	private static AuthorModel instance = null;
	
	public static AuthorModel getInstance() {
		if (instance == null) {
			instance = new AuthorModel();
		}
		
		return instance;
	}
	
	private AuthorModel() {
		try {
			ObjectifyService.register(Author.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<Author> list(int page, int limit) {
		List<Author> authors = new ArrayList<Author>();
		
		int start = (page - 1) * limit;
		authors = ofy.query(Author.class).limit(limit).offset(start).list();
			
		
		return authors;
	}
	
	public void insert(Author author) {
		ofy.put(author);
	}
	
	public void delete(Author author) {
		
		ofy.delete(author);
	}
	
	public Author getAuthor(String id) {
		Author author = new Author();
		try {
			author = ofy.get(new Key<Author>(Author.class, id));
		} catch (Exception e) {
			author = null;
		}
		return author;
	}
	
	public Author getAuthorByUrl(String url) {
		Author author = new Author();
		
		String cacheName = prefix + url;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				author = (Author) cache.get(cacheName);
				if (author != null) isCached = true;
			} catch (Exception e) {
			}
		}
		
		if (!isCached) {
			try {
				author = ofy.query(Author.class).filter("url", url).get();
			} catch (Exception e) {
				author = null;
			}
			
			if (author != null && cache != null) {
				cache.put(cacheName, author);
			}
			
		}
		
		
		return author;
	}
	
	public Map<String, Author> getByListIds(List<String> ids) {
		Map<String, Author> authors = new TreeMap<String, Author>();
		try {
			authors = ofy.get(Author.class, ids);
		} catch (Exception e) {
			authors = new TreeMap<String, Author>();
		}
		
		
		return authors;
	}
	
	
	public boolean checkAuthorExists(String id) {
		boolean exists = false;
		Author author = getAuthor(id);
		if (author != null) {
			exists = true;
		}
		return exists;
	}
	
	public boolean checkAuthorExistsByUrl(String url) {
		boolean exists = false;
		Author author = getAuthorByUrl(url);
		if (author != null) {
			exists = true;
		}
		return exists;
	}
}
